<!-- 异常操作界面1 -->
<template>
	<view>
		<view v-if="exp !== '死种' && exp !== '死仔'">
			<view class="ul" :class="cageCount > 6 ? 'ul-8' : 'ul-6'">
				<view v-for="(item,index) in displayList" :key="index" class="li" @tap="submit(item,exp)"
					@longpress="longPress(item)" @touchend="tounchend()" :style="Styles(item)">
					<span v-if="abnormalList[item-1] && abnormalList[item-1].refer"
						style="position: absolute;top:-55rpx;font-size: 20rpx;">记录中</span>
					<span class="cage-number">{{item}}</span>
					<!-- 显示鸽笼数量 -->
					<view class="cage-info" v-if="cageNum[item-1]">
						<text class="number">{{ cageNum[item-1].number || 0 }}</text>
						<text class="cub-number" v-if="cageNum[item-1].cub_number">仔:{{ cageNum[item-1].cub_number }}</text>
					</view>
				</view>
			</view>
		</view>
		<!-- 组件提示框 -->
		<u-toast ref="uToast" />
	</view>
</template>

<script>
	import {
		reqAbnormal,
		reqRecordOut,
		getExpection,
		reqExpection,
		deleteAbnormal
	} from '@/api/index.js'
	import {
		getNowDate
	} from '@/getTime.js'
	import {
		mapGetters
	} from 'vuex'
	import abnormal from '../../store/modules/abnormal';
	export default {
		components: {},
		props: {
			bgColor: {
				type: Array,
				required: true,
				validator: function(value) {
					return value.every(item => typeof item === 'string');
				}
			},
			chooseBgColor: {
				type: String,
				required: false
			},
			exp: {
				type: String,
				required: true
			},
			abnormal: {
				type: String,
				required: true
			},
			cageNum: {
				type: Array,
				default: () => []
			},
			cageCount: {
				type: Number,
				default: 6
			}
		},
		data() {
			return {
				list: [1, 4, 2, 5, 3, 6], // 默认6个鸽笼的布局
				list8: [1, 5, 2, 6, 3, 7, 4, 8], // 8个鸽笼的布局
				abnormalList: [],
				formData: {
					siteId: uni.getStorageSync('siteId'),
					houseId: '',
					cageId: '',
					refer: ''
				},
				handle: '',
				show: false,
				content: '确认操作吗?',
				index: '',
				islongPress: false,
				connect: false,
				path: '',
			}
		},
		computed: {
			...mapGetters(['nfcId']),
			// 根据鸽笼数量动态显示列表
			displayList() {
				return this.cageCount > 6 ? this.list8.slice(0, this.cageCount) : this.list.slice(0, this.cageCount);
			}
		},
		 mounted() {
		        // 监听仓号变更事件
		        this.$cage.$on('siteChanged', this.handleSiteChange);
				 // 监听全局事件
				this.requestAbnormal(); // 初始化请求异常状态
				this.$cage.$on('sednAbnormal', this.send);
				this.$cage.$on('abnormalsettle', this.Settle);
				this.$cage.$on('withdraw', this.withdraw);
		    },
		    beforeDestroy() {
		        // 组件销毁前取消监听
		        this.$cage.$off('siteChanged', this.handleSiteChange);
				 // 新增：移除蓝牙事件监听
				    this.$cage.$off('sednAbnormal', this.send);
				    this.$cage.$off('abnormalsettle', this.Settle);
				    this.$cage.$off('withdraw', this.withdraw);
		    },
		methods: {
			// 新增：处理仓号变更事件
			    handleSiteChange() {
			        this.requestAbnormal(); // 重新请求异常数据
			    },
			throttle(func, delay) {
				let lastCall = 0;
				let timeoutId;

				return function(...args) {
					const now = Date.now();

					if (now - lastCall >= delay) {
						func.apply(this, args);
						lastCall = now;
					} else {
						clearTimeout(timeoutId);
						timeoutId = setTimeout(() => {
							func.apply(this, args);
							lastCall = Date.now();
						}, delay - (now - lastCall));
					}
				};
			},
			
			Styles(item) {
				if (this.abnormalList[item - 1] && this.abnormalList[item - 1].refer) {
					return {
						position: 'relative',
						background: this.bgColor[1]
					}
				} else {
					return {
						backgroundColor: this.bgColor[0]
					}
				}
			},
			
			async send({
				abnormal,
				cageId
			}) {
				if (abnormal === this.abnormal) {
					const throttledSendAbnormal = this.throttle(async () => {
						await this.sendAbnormal(cageId, this.exp);
					}, 2000);
					throttledSendAbnormal();
				}
			},
			
			async Settle({
				abnormal,
				cageId
			}) {
				if (abnormal === this.abnormal) {
					const throttledabnormalSettle = this.throttle(async () => {
						await this.abnormalSettle(cageId, this.exp);
					}, 2000);
					throttledabnormalSettle();
				}
			},
			
			async withdraw({
				abnormal,
				cageId
			}) {
				if (abnormal === this.abnormal) {
					const throttledabnormalwithdraw = this.throttle(async () => {
						await this.longPress(cageId, this.exp);
					}, 2000);
					throttledabnormalwithdraw();
				}
			},
			
			async requestAbnormal() {
				try {
					const obj = {
						siteId: uni.getStorageSync('siteId'),
						houseId: this.nfcId,
						operation: this.abnormal
					}
					const res = await getExpection(obj);
					this.abnormalList = res.abnormal
				} catch (error) {
					console.log('异常', error);
				}
			},
			
			sendAbnormal(i, exp) {
				this.formData.cageId = i;
				this.formData.houseId = this.$store.state.NFC.nfcId;
				this.formData.refer = exp;
				this.$loading();

				if (exp === '淘汰') {
					reqRecordOut(this.formData).then(resp => {
						if (resp.msg === '已存在未处理的淘汰记录') {
							this.$refs.uToast.show({
								title: `${i}笼已是${exp}状态`,
								type: 'warning',
								duration: '800',
								position: 'top'
							});
						} else {
							const obj1 = {
								siteId: uni.getStorageSync('siteId'),
								houseId: this.nfcId
							};
							this.$store.dispatch('getStatu', obj1);
							const obj2 = {
								siteId: uni.getStorageSync('siteId'),
								houseId: this.nfcId,
								twoOrSix: 3
							};
							this.$store.dispatch('getDate', obj2);
							this.$refs.uToast.show({
								title: `已记录${i}笼${exp}异常`,
								type: 'success',
								duration: '800',
								position: 'top'
							});
							this.requestAbnormal();
						}
					}).finally(() => {
						this.$hide();
					});
				} else {
					reqAbnormal(this.formData).then(data => {
						if (data.msg === '已存在') {
							this.$refs.uToast.show({
								title: `${i}笼已是${exp}状态`,
								type: 'warning',
								duration: '800',
								position: 'top'
							});
						} else {
							if (data.code === 200) {
								const obj1 = {
									siteId: uni.getStorageSync('siteId'),
									houseId: this.nfcId
								};
								this.$store.dispatch('getStatu', obj1);
								const obj2 = {
									siteId: uni.getStorageSync('siteId'),
									houseId: this.nfcId,
									twoOrSix: 3
								};
								this.$store.dispatch('getDate', obj2);
								this.$refs.uToast.show({
									title: `已记录${i}笼${exp}异常`,
									type: 'success',
									duration: '800',
									position: 'top'
								});
								this.requestAbnormal();
							} else {
								this.$refs.uToast.show({
									title: data.msg,
									type: 'error',
									duration: '800',
									position: 'top'
								});
							}
						}
					}).catch(() => {
						this.$hide();
						this.$refs.uToast.show({
							title: data.msg,
							type: 'error',
							duration: '800',
							position: 'top'
						});
					}).finally(() => {
						this.$hide();
					});
				}
			},
			
			async abnormalSettle(item, exp) {
				if (this.abnormalList[item - 1] && this.abnormalList[item - 1].id) {
					const obj = {
						siteId: uni.getStorageSync('siteId'),
						cageId: item,
						houseId: this.nfcId,
						refer: exp,
						updateTime: getNowDate()
					};
					try {
						const response = await reqExpection(obj)
						if (response.code == 200) {
							this.requestAbnormal()
							this.$refs.uToast.show({
								title: `已解决${item}笼${this.exp}异常`,
								type: 'success',
								duration: '800',
								position: 'top',
							})
						} else {
							this.$refs.uToast.show({
								title: `解决${item}笼${this.exp}异常失败`,
								type: 'error',
								duration: '800',
								position: 'top',
							})
						}
					} catch (error) {
						console.error('请求错误', error);
					}
				} else {
					this.$refs.uToast.show({
						title: `未记录，无法解决 cage为${item}`,
						type: 'error',
						duration: '800',
						position: 'top',
					})
				}
			},
			
			tounchend() {
				setTimeout(() => {
					this.islongPress = false
				}, 200)
			},
			
			async longPress(item) {
				console.log('长按事件');
				this.islongPress = true;
				if (this.abnormalList[item - 1] && this.abnormalList[item - 1].id) {
					const obj = {
						operation: this.abnormal,
						id: this.abnormalList[item - 1].id,
						siteId: uni.getStorageSync('siteId'),
						cageId: item,
						houseId: this.nfcId,
						time: this.abnormalList[item - 1].time
					};
					try {
						const response = await deleteAbnormal(obj)
						if (response.code == 200) {
							this.requestAbnormal()
							this.$refs.uToast.show({
								title: `已撤回${item}笼${this.exp}异常`,
								type: 'warning',
								duration: '800',
								position: 'top',
							})
						} else {
							this.$refs.uToast.show({
								title: `撤回${item}笼${this.exp}异常失败`,
								type: 'error',
								duration: '800',
								position: 'top',
							})
						}
					} catch (error) {
						console.error('请求错误', error);
					}
				} else {
					this.$refs.uToast.show({
						title: `未记录，撤回${item}笼${this.exp}异常失败`,
						type: 'error',
						duration: '800',
						position: 'top',
					})
				}
			},
			
			submit(item, exp) {
				this.cage_id = item.cage_id
				if (this.islongPress === false) {
					let _this = this
					let curTime = new Date().getTime()
					let lastTime = this.lastTime
					_this.lastTime = curTime
					let diff = curTime - lastTime;
					console.log('diff', diff)
					if (diff < 300) {
						setTimeout(() => {
							this.abnormalSettle(item, exp);
							clearTimeout(_this.timer)
						})
					} else {
						_this.timer = setTimeout(() => {
							this.sendAbnormal(item, exp)
						}, 300)
					}
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.ul-6 {
		display: flex;
		justify-content: space-around;
		align-content: space-around;
		width: 100%;
		height: 100%;
		flex-wrap: wrap;
		margin-top: 36.23rpx;

		.li {
			display: flex;
			flex-direction: column;
			margin: 32.91rpx 32.91rpx;
			text-align: center;
			align-items: center;
			width: 137.11rpx;
			height: 137.11rpx;
			line-height: 149.91rpx;
			font-size: 102.38rpx;
			font-weight: 700;
			list-style: none;
			border-radius: 36.23rpx;
			color: #fff;
			font-family: 'ExpectionNumber';
			position: relative;

			.cage-number {
				font-size: 102.38rpx;
			}

			.cage-info {
				position: absolute;
				bottom: 5rpx;
				left: 0;
				right: 0;
				display: flex;
				flex-direction: column;
				align-items: center;
				font-size: 20rpx;
				line-height: 1.2;

				.number {
					font-weight: bold;
					margin-bottom: 2rpx;
				}

				.cub-number {
					font-size: 18rpx;
					color: rgba(255, 255, 255, 0.9);
				}
			}
		}
	}

	.ul-8 {
		display: flex;
		justify-content: space-around;
		align-content: space-around;
		width: 100%;
		height: 100%;
		flex-wrap: wrap;
		margin-top: 20rpx;

		.li {
			display: flex;
			flex-direction: column;
			margin: 20rpx 15rpx;
			text-align: center;
			align-items: center;
			width: 120rpx;
			height: 120rpx;
			line-height: 130rpx;
			font-size: 90rpx;
			font-weight: 700;
			list-style: none;
			border-radius: 30rpx;
			color: #fff;
			font-family: 'ExpectionNumber';
			position: relative;

			.cage-number {
				font-size: 90rpx;
			}

			.cage-info {
				position: absolute;
				bottom: 3rpx;
				left: 0;
				right: 0;
				display: flex;
				flex-direction: column;
				align-items: center;
				font-size: 18rpx;
				line-height: 1.2;

				.number {
					font-weight: bold;
					margin-bottom: 1rpx;
				}

				.cub-number {
					font-size: 16rpx;
					color: rgba(255, 255, 255, 0.9);
				}
			}
		}
	}

	.exception_gray {
		position: relative;
		background: linear-gradient(135deg, #754359, #a92232 100%) !important;
		color: #fff;
	}
</style>